package cn.itcast.bos.action.base.take_delivery;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.web.action.common.BaseAction;
/**
 * 处理文件上传相关方法
 * @author 艾欣
 *
 */
@ParentPackage("json-default")
@Scope("prototype")
@Namespace("/")
@Controller
public class ImageAction extends BaseAction<Object> {
	private File imgFile;
	private String imgFileFileName;
	private String imgFileContentType;

	public void setImgFile(File imgFile) {
		this.imgFile = imgFile;
	}

	public void setImgFileFileName(String imgFileName) {
		this.imgFileFileName = imgFileName;
	}

	public void setImgFileContentType(String imgFileContentType) {
		this.imgFileContentType = imgFileContentType;
	}

	// 文件上传
	@Action(value = "image_upload", results = { @Result(name = "success", type = "json") })
	public String upload() throws IOException {
		//文件保存的绝对路径
		String savePath = ServletActionContext.getServletContext().getRealPath(
				"/upload/");
		//相对路径
		String saveUrl = ServletActionContext.getRequest().getContextPath()
				+ "/upload/";
		//生成随机图片名
		UUID uuid = UUID.randomUUID();
		//拼接图片名防止重名
		String ext = imgFileFileName
				.substring(imgFileFileName.lastIndexOf("."));
		String randomFileName=uuid+ext;
		//保存图片
		File destFile = new File(savePath+"/"+randomFileName);
		FileUtils.copyFile(imgFile, destFile);
		//通知浏览器上传成功
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("error", 0);
		result.put("url", saveUrl + randomFileName); // 返回相对路径
		ActionContext.getContext().getValueStack().push(result);
		
		return SUCCESS;

	}
}
